<?php
/**
 * Created by PhpStorm.
 * User: kcj
 * Date: 2017/3/10
 * Time: 11:12
 * 房间管理类
 */
namespace app\index\controller;

use app\common\RedisDB;
use think\Controller;

use GatewayClient\Gateway;
use app\index\model\UserModel;
use app\index\model\RoomModel;

class Gameroom extends Controller
{
    private static $roomDiamond = 0;
    private $mUser;
    

    public function __construct()
    {
        header("Access-Control-Allow-Origin: *");
//        if(!session('?uid')) {
//            session('uid','oibzjw4L_q2FGufK6hNBjTc82i-w');
////            session('lasturl','http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
////            $this->loginByWX();
//        }
        //$this->mUser = User::get(session('uid'));

    }

    public function test()
    {
        RedisDB::factory("wtimer")->set("gameroom/delroombyurl/roomid",3232);
       // RedisDB::factory("wtimer")->del("gameroom/delroombyurl/roomid");
        print_r(RedisDB::factory("wtimer")->get("gameroom/delroombyurl/roomid"));
        print_r(123);
    }
    
    public function delroombyurl($roomid)
    {
        $game = new RoomModel(null,$roomid);
        $game->delroom();
    }

    public function clearroom()
    {
        $keys = RedisDB::factory("game")->getKeys("*");
        foreach($keys as $key)
        {
            $prefix = RedisDB::factory("game")->getOption(\Redis::OPT_PREFIX);
            $key = substr($key,strlen($prefix));
            print_r(RedisDB::factory("game")->del($key));
        }
    }


    private function getGame($uid)
    {
        $mUser=new UserModel($uid);
        $user = $mUser->getInfo();
        if(empty($user['roomid'])){
            return false;
        }

        return new RoomModel($mUser, $user['roomid']);
    }
    
    public function feed($uid)
    {
        $game = $this->getGame($uid);
        if(!$game->feed()){
            $this->error($game->getError());
        }
    }

    public function autofeed()
    {
        $data['roominfo']=$_POST['error'];
        db('feed_test')->insert($data);
    }

    public function ready($uid)
    {
        $game = $this->getGame($uid);
        if(!$game->ready()){
            $this->error($game->getError());
        }
    }

    public function bstart($uid)
    {
        $game = $this->getGame($uid);
        if(!$game->bstart()){
            $this->error($game->getError());
        }
    }

    public function nextround($carry,$uid)
    {
        $game = $this->getGame($uid);
        if(!$game->nextRound($carry+0)){
            $this->error($game->getError());
        }
    }

    public function setmultiples($multiple,$uid)
    {
        $game = $this->getGame($uid);
        if(!$game->onmultiple($multiple)){
            $this->error($game->getError());
        }
    }

    public function repair($uid,$checktrust=false)
    {
        $game = $this->getGame($uid);
        if(!$game->repair(true,$checktrust)){
            $this->error($game->getError());
        }
    }

    public function norepair($uid,$checktrust=false)
    {
        $game = $this->getGame($uid);
        if(!$game->repair(false,$checktrust)){
            $this->error($game->getError());
        }
    }

    public function zhuang($uid)
    {
        $game = $this->getGame($uid);
        if(!$game->ready(true)){
            $this->error($game->getError());
        }
    }

    public function info($uid)
    {
        Gateway::$registerAddress = GATEWAYADDRESS;
        $game = $this->getGame($uid);
        if($game===false)
        {
            $json=array('type'=>'Error','data'=>"GetRoomFalied");
            Gateway::sendToUid($uid, json_encode($json));
        }
        $room = $game->getInfoEx();
        $json=array('type'=>'Room.info','data'=>$room);
        Gateway::sendToUid($uid, json_encode($json));

    }

    public  function balance()
    {
        $uid='oibzjw4L_q2FGufK6hNBjTc82i-y';
        $game = $this->getGame($uid);
        $game->redis->hSet("room:".$game->getId(),'joker',204);
        $card = array(110,405);
        $zhuangcard=array(113,112,201);
        print_r($game->getCardType($card));
        print_r($game->getCardType($zhuangcard));

        print_r($game->balance($card,$zhuangcard));
    }

    public  function trust($uid,$trust)
    {
        $game = $this->getGame($uid);
        $user=new UserModel($uid);
        $seatid=$user->getInfo()['seatid'];
        if(!$game->setTrust($seatid,$trust))
        {
            $this->error($game->getError());
        }
    }

    public function updatestate($roomid,$started,$state,$seatid=0,$round)
    {
            $game = new RoomModel(null, $roomid);
        if($game->getInfo()['currentround']==$round)
            $game->updatestate($game->getInfo(), $started, $state, $seatid);
        print_r("ok");
    }

    public function setOvettimer($uid)
    {
        $game = $this->getGame($uid);
        $user=new UserModel($uid);
        $user=$user->getInfo();
        $game->setOvertimer($user['seatid']);
    }

    public  function gettype()
    {
        //$uid='oZiF30lYmQiw0md5nyJAWTow7HJE';
        $uid='oibzjw4L_q2FGufK6hNBjTc82i-y';
        $game = $this->getGame($uid);
        //print_r(' getRepairCount'.$game->getRepairCount($game->getInfo()).' ');
        $card1 = array(105,101);
        $card = array(205,301);
        $jnum = $game->getInfo()['joker']%100;
        foreach($card as $k=>$v)
        {
            if($v%100==$jnum)
                $card[$k]="501";
        }
        foreach($card1 as $k=>$v)
        {
            if($v%100==$jnum)
                $card1[$k]="501";
        }
        print_r($card);
        print_r($game->getCardType($card));
        print_r($card1);
        print_r($game->getCardType($card1));
        print_r($game->balance($card,$card1));
//        $room=$game->getInfo();
//        if($room['type']==1) {
//            $maxcard = $room["seat{$room['zhuangid']}"]['cards'];
//            $jnum = $room['joker'] % 100;
//            foreach ($maxcard as $k => $v) {
//                if ($v % 100 == $jnum)
//                    $maxcard[$k] = "501";
//            }
//            for ($i = 1; $i <= 8; ++$i) {
//                if (!isset($room["seat$i"]) || $i == $room['zhuangid']) {
//                    continue;
//                }
//                print_r(($room['currentround']));
//                $seat = $room["seat$i"];
//                if ($seat['carry'] == 1 && ($room['currentround']) % 4 == 0) {
//                    $jnum = $room['joker'] % 100;
//                    $card = $seat['cards'];
//                    if (count($card) < 2) continue;
//                    foreach ($card as $k => $v) {
//                        if ($v % 100 == $jnum)
//                            $card[$k] = "501";
//                    }
//                    if ($maxcard == null || ($this->balance($card, $maxcard) > 0)) {
//                        $room['zhuangid'] = $i;
//                        print_r($i);
//                        $maxcard = $seat['cards'];
//                    }
//                }
//            }
//        }
    }

    public function testopenbrand()
    {
        $room['seat1']=array('cards'=>array(412,408));
        $room['seat2']=array('cards'=>array(408,206,403));
        $room['seat3']=array('cards'=>array(413,311,404));
        $room['joker']=204;
        for ($i = 1; $i <= 8; ++$i) {
            if (!isset($room["seat$i"])) {
                continue;
            }
            $seat1 = $room["seat$i"];
            $card1 = $seat1['cards'];
            if(count($card1)<2)continue;
            $jnum = $room['joker'] % 100;
            foreach ($card1 as $k => $v) {
                if ($v % 100 == $jnum)
                    $card1[$k] = "501";
            }
            $result[$i] = (new RoomModel(null))->getCardType($card1);
        }
        for ($i = 1; $i <= 8; ++$i) {
            if (!isset($room["seat$i"])) {
                continue;
            }
            $seat1 = $room["seat$i"];
            $card1 = $seat1['cards'];
            if(count($card1)<2)continue;
            $jnum = $room['joker'] % 100;
            foreach ($card1 as $k => $v) {
                if ($v % 100 == $jnum)
                    $card1[$k] = "501";
            }
            for ($j = $i + 1; $j <= 8; ++$j) {
                if (!isset($room["seat$j"])) {
                    continue;
                }
                $seat2 = $room["seat$j"];
                $card2 = $seat2['cards'];
                if(count($card2)<2)continue;
                $jnum = $room['joker'] % 100;
                foreach ($card2 as $k => $v) {
                    if ($v % 100 == $jnum)
                        $card2[$k] = "501";
                }
                $r = (new RoomModel(null))->balance($card1, $card2);
                $result[$i]['scores'] += $r;// *$seat1['multiples'];
                $result[$j]['scores'] -= $r;// * $seat2['multiples'];
            }
        }
        print_r($result);
    }

    public function playrecord($uid,$serveid)
    {
        $game = $this->getGame($uid);
        if(!$game->speak($serveid))
        {

        }

    }

    public function speak1($serveid)
    {
        $access_token = $this->getAccessToken();

        $path = "./weixinrecord/";   //保存路径，相对当前文件的路径
        $outPath = "./php/weixinrecord/";  //输出路径，给show.php 文件用，上一级

        if(!is_dir($path)){
            mkdir($path);
        }

        //微 信上传下载媒体文件
        $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id={$serveid}";

        $filename = "wxupload_".time().rand(1111,9999).".amr";
        $this->downAndSaveFile($url,$path.$filename);
        return true;
    }

    public function downAndSaveFile($url,$savePath){
        ob_start();
        readfile($url);
        $img  = ob_get_contents();
        ob_end_clean();
        $size = strlen($img);
        $fp = fopen($savePath, 'a');
        fwrite($fp, $img);
        fclose($fp);
    }

    //获取Token
    function getAccessToken() {
        //  access_token 应该全局存储与更新，以下代码以写入到文件中做示例
        $data = json_decode(file_get_contents("./access_token.json"));
        if ($data->expire_time < time()) {
            $appid = config("wxconfig.appid");
            $appsecret = config("wxconfig.appsecret");
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
            $res = json_decode($this->httpGet($url));
            $access_token = $res->access_token;
            if ($access_token) {
                $data->expire_time = time() + 7000;
                $data->access_token = $access_token;
                $fp = fopen("./access_token.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        }
        else {
            $access_token = $data->access_token;
        }
        return $access_token;
    }

    function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }

    public function addDiamond($num)
    {
        $uid="oibzjw4L_q2FGufK6hNBjTc82i-y";
        $mUser = new UserModel($uid);
        $mUser->addDiamond($num );
    }

    public function talk($uid,$sound)
    {
        $game = $this->getGame($uid);
        if(!$game->talk($sound))
        {

        }
    }

    public function disband($uid)
    {
        $game = $this->getGame($uid);
        if(!$game->disband()){
            $this->error($game->getError());
        }
    }

    public function setTrustReady($roomid,$round)
    {
        $game=new RoomModel(null,$roomid);
        if($game->getInfo()['currentround']==$round)
        $game->setTrustReady();
        print_r("ok");
    }

    public function setTrustRepair($roomid,$seatid,$round)
    {
        $game=new RoomModel(null,$roomid);
        if($game->getInfo()['currentround']==$round)
        $game->checkTrusInRepair($seatid,$game->getInfo());
        print_r("ok");

    }

    public function setTrustMultiple($roomid,$round)
    {
        $game=new RoomModel(null,$roomid);
        if($game->getInfo()['currentround']==$round)
        $game->setTrustMultiple();
        print_r("ok");
    }

    public function dodisband($uid,$disband)
    {
        $game = $this->getGame($uid);
        if(!$game->dodisband($disband)){
            $this->error($game->getError());
        }
    }

    public  function updategame($uid,$round,$type,$jcard,$multiples)
    {
        $game = $this->getGame($uid);
        if(!$game->updategame($round,$type,$jcard,$multiples)){
            $this->error($game->getError());
        }
    }

    public function outroom($uid)
    {
        $game = $this->getGame($uid);
        $u=(new UserModel($uid))->getInfo();
        if(!$game->outroom($u['seatid'])){
            $this->error($game->getError());
        }
    }
    public function updatescores($uid)
    {
        $game = $this->getGame($uid);
        if(!$game->updatescores()){
            $this->error($game->getError());
        }
    }

}